import { useState } from 'react'
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import { ScrollArea } from "@/components/ui/scroll-area"
import { format, differenceInHours } from 'date-fns'
import ComboboxMultiGroupSelector from "@/components/ComboboxMultiGroupSelector"
import CommonSelector from '@/components/CommonSelector'

export default function AppointmentForm({
  currentUser,
  branchCampus,
  coaches,
  clientAndCoursePackages,
  selectedTimeRange,  // 已选择的时间范围
  selectedCourt,      // 已选择的场地
}) {
  // 状态管理
  const [selectedClientsWithPackages, setSelectedClientsWithPackages] = useState([])
  const [selectedAssistantsWithRates, setSelectedAssistantsWithRates] = useState([]) // 选中的助教
  const [memo, setMemo] = useState('')                // 备注

  // 处理助教选择
  const handleAssistantToggle = (assistantId) => {
    setSelectedAssistantsWithRates(prev => {
      if (prev.some(assistant => assistant.assistant_id === assistantId)) {
        return prev.filter(assistant => assistant.assistant_id !== assistantId)
      } else {
        return [...prev, { assistant_id: assistantId, rate: 3}]
      }
    })
  }

  // 处理助教提成比例变更
  const updateAssistantCommissionRate = (assistantId, rate) => {
    setSelectedAssistantsWithRates(prev => {
      return prev.map(assistant => {
        if (assistant.assistant_id === assistantId) {
          return { ...assistant, rate: parseFloat(rate) }
        }
        return assistant
      })
    })
  }

  return (
    <div className="space-y-2 py-1">
    <Input type="hidden" name="branch_campus_id" value={branchCampus.id} />
    <Input type="hidden" name="start_time" value={selectedTimeRange.start} />
    <Input type="hidden" name="end_time" value={selectedTimeRange.end} />
    <Input type="hidden" name="court_id" value={selectedCourt?.id} />
    <Input type="hidden" name="selected_coaches_with_rates" value={JSON.stringify(selectedAssistantsWithRates)} />
    <Input type="hidden" name="selected_clients_with_packages" value={JSON.stringify(selectedClientsWithPackages)} />
      {/* 校区 */}
      <div className="flex flex-row items-center gap-2">
        <Label className="w-24">当前校区:</Label>
        <span className="text-sm">{branchCampus.name}</span>
      </div>
      {/* 显示已选择的时间和场地信息 */}
      <div className="flex flex-row items-center gap-2">
        <Label className="w-24">预约时间：</Label>
        <span className="text-sm">{format(selectedTimeRange.start, 'yyyy-MM-dd HH:mm')} - {format(selectedTimeRange.end, 'HH:mm')}</span>
      </div>
      {/* 课时 */}
      <div className="flex flex-row items-center gap-2">
        <Label className="w-24">训练课时：</Label>
        <span className="text-sm">{differenceInHours(selectedTimeRange.end, selectedTimeRange.start)}</span>
      </div>
      <div className="flex flex-row items-center gap-2">
        <Label className="w-24">当前场地：</Label>
        <span className="text-sm">{selectedCourt?.name}</span>
      </div>

      {/* 主教练 */}
      <div className="flex flex-row items-center gap-2">
        <Label className="w-24">主教练：</Label>
       <div className="w-1/2">
       <CommonSelector
          name="coach_id"
          items={coaches.map(coach => ({
            label: coach.name,
            value: coach.id
          }))}
          placeholder="选择主教练"
          label="主教练"
          defaultValue={currentUser.id}
        />
       </div>
      </div>
      {/* {主教课程提成} */}
      <div className="flex flex-row items-center gap-2">
        <Label className="w-24">主教提成:</Label>
        <Input
          name="teaching_commission_rate"
          type="number"
          placeholder="设置提成比例"
          className="h-8 w-1/2"
          defaultValue={3}
        />
        <span className="text-sm">%</span>
      </div>
      {/* 使用级联多选组件 */}
      <div className="space-y-2">
        <Label>选择学员和课程包[可选多学员]:</Label>
        <ComboboxMultiGroupSelector
          options={clientAndCoursePackages}
          value={selectedClientsWithPackages}
          onChange={setSelectedClientsWithPackages}
          placeholder="选择学员和课程包"
          emptyText="没有可用的学员或课程包"
          searchPlaceholder="搜索学员或课程包..."
        />
      </div>

      {/* 选择助教 */}
      <div className="space-y-2">
        <Label>设置助教及提成比例[可选多助教]:</Label>
        <ScrollArea className="h-[150px] border rounded-md p-2">
          {coaches.map(coach => (
            <div key={coach.id} className="flex p-2 items-center justify-start space-x-2  border-b">
            <Checkbox
                  checked={selectedAssistantsWithRates.some(assistant => assistant.assistant_id === coach.id)}
                onCheckedChange={() => handleAssistantToggle(coach.id)}
              />
              <div className='flex flex-col items-start justify-center'>
                <span className='text-sm'>{coach.name}</span>
                {selectedAssistantsWithRates.some(assistant => assistant.assistant_id === coach.id) && (
                <div className='flex items-center space-x-2'>
                  <span className='text-sm'>提成比例:</span>
                  <Input
                    type="number"
                    placeholder="设置提成比例"
                    className="w-24 h-8"
                    defaultValue={selectedAssistantsWithRates.find(assistant => assistant.assistant_id === coach.id)?.rate || 3}
                    onChange={(e) => updateAssistantCommissionRate(coach.id, e.target.value)}
                  />
                  <span className='text-sm'>%</span>
                </div>
                )}
              </div>
            </div>

          ))}
        </ScrollArea>
      </div>

      {/* 备注 */}
      <div className="space-y-2 ">
        <Label>备注[选填]:</Label>
        <Input
          name="memo"
          value={memo}
          onChange={(e) => setMemo(e.target.value)}
          placeholder="添加备注信息"
        />
      </div>
    </div>
  )
}